package com.micro.disk.user.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.micro.db.dao.DiskUserDao;
import com.micro.db.dao.LoginTokenDao;
import com.micro.db.jdbc.DiskOrganizationJdbc;
import com.micro.db.jdbc.DiskUserJdbc;
import com.micro.model.DiskUser;
import com.micro.model.LoginToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.micro.disk.user.bean.Page;
import com.micro.disk.user.bean.SessionUserBean;
import com.micro.disk.user.bean.TreeJson;
import com.micro.disk.user.bean.UserBean;
import com.micro.disk.user.service.UserService;
import com.micro.common.DateUtils;

@Service(interfaceClass=UserService.class)
@Component
@Transactional
public class UserServiceImpl implements UserService{
	@Autowired
	private DiskUserDao diskUserDao;
	@Autowired
	private LoginTokenDao loginTokenDao;
	@Autowired
	private DiskUserJdbc diskUserJdbc;
	@Autowired
	private DiskOrganizationJdbc diskOrganizationJdbc;

	@Override
	public Page<UserBean> findUserPageList(Integer page, Integer limit, String username, String nickname) {
		Page<UserBean> p=diskUserJdbc.findUserBeanList(page, limit,username,nickname);
		return p;
	}

	@Override
	public List<TreeJson> findUserTree(String pid, String type) {
		List<TreeJson> trees = new ArrayList<TreeJson>();
		if("org".equals(type)){
			trees=diskOrganizationJdbc.findChildrenTreeJsonList(pid,type);
		}else{
			trees = diskOrganizationJdbc.findTreeJsonList(type);
		}
		return trees;
	}

	@Override
	public SessionUserBean login(String username, String password) {
		if(StringUtils.isEmpty(username)){
			throw new RuntimeException("用户名不能为空!");
		}
		if(StringUtils.isEmpty(password)){
			throw new RuntimeException("密码不能为空!");
		}
		DiskUser user = diskUserDao.findUserByUsername(username);
		if(null != user){
			SessionUserBean bean=new SessionUserBean();
			if(password.equalsIgnoreCase(user.getPassword())){
				//save token
				LoginToken lt = generateToken(username);
				loginTokenDao.save(lt);
				//存储登录信息
				bean.setId(user.getId());
				bean.setNickname(user.getNickname());
				bean.setUsername(user.getUsername());
				bean.setTelephone(user.getTelephone());
				bean.setToken(lt.getToken());
				return bean;
			}else{
				throw new RuntimeException("用户名或密码错误!");
			}
		}else{
			throw new RuntimeException("用户不存在或已被删除!");
		}

	}

	@Override
	public SessionUserBean getUserByToken(String token) {
		SessionUserBean bean=new SessionUserBean();
		if(!StringUtils.isEmpty(token)){
			LoginToken lt = loginTokenDao.findByUsernameByToken(token,DateUtils.parseDate(DateUtils.getCurrentTime(),"yyyy-MM-dd HH:mm:ss"));
			if(null != lt){
				DiskUser user = diskUserDao.findUserByUsername(lt.getUsername());
				if(null!=user){
					bean.setId(user.getId());
					bean.setNickname(user.getNickname());
					bean.setUsername(user.getUsername());
					bean.setTelephone(user.getTelephone());
					bean.setToken(token);
					return bean;
				}
			}
		}
		return null;
	}

	@Override
	public void logout(String token) {
		
	}
	@Override
	public SessionUserBean findUserWithPwd(String userName, String password){
		SessionUserBean sessionUserBean = new SessionUserBean();
		if(StringUtils.isEmpty(userName)){
			throw new RuntimeException("用户名不能为空!");
		}
		if(StringUtils.isEmpty(password)){
			throw new RuntimeException("密码不能为空!");
		}
		DiskUser user = diskUserDao.findUserByUsernameAndPwd(userName,password);
		if(null == user){
			throw new RuntimeException("用户原密码不对!");

		}else{
			sessionUserBean.setId(user.getId());
			sessionUserBean.setNickname(user.getNickname());
			sessionUserBean.setUsername(user.getUsername());
			sessionUserBean.setTelephone(user.getTelephone());
		}
		return sessionUserBean;
	}

	@Override
	public void updateUserPwd(String userName, String password){
		diskUserDao.updateUserPwd(userName,password);
	}

	@Override
	public void updateUserPwdByID(String userId, String password){
		diskUserDao.updateUserPwdById(userId,password);
	}

	@Override
	public void insertUser(String username,String nickname,String telephone,String password){
		//先查账号是否重复
		DiskUser existUser = diskUserDao.findUserByUsername(username);
		if(null !=existUser){
			throw new RuntimeException("用户账号已经存在，不可重复添加!");
		}else{
			DiskUser user = new DiskUser();
			user.setId(java.util.UUID.randomUUID().toString());
			user.setNickname(nickname);
			user.setUsername(username);
			user.setTelephone(telephone);
			user.setPassword(password);
			user.setOrgid("0");//默认到根目录
			user.setState(1);//默认有效
			diskUserDao.save(user);
		}
	}

	/**
	 * 新增用户
	 *
	 * @param userid
	 * @param nickname
	 * @param telephone
	 * @return
	 */
	@Override
	public void updateUserInfo(String userid, String nickname, String telephone) {
		diskUserDao.updateUserPartInfo(userid,nickname,telephone);
	}

	/**
	 * 逻辑删除用户
	 *
	 * @param userid
	 */
	@Override
	public void invalidUser(String userid) {
		diskUserDao.logicDeleleUser(userid);
	}


	public LoginToken generateToken(String username){
		LoginToken lt = new LoginToken();
		lt.setId(java.util.UUID.randomUUID().toString());
		lt.setUsername(username);
		lt.setToken(java.util.UUID.randomUUID().toString());
		lt.setCreatetime(DateUtils.parseDate(DateUtils.getCurrentTime(),"yyyy-MM-dd HH:mm:ss"));
		lt.setExpiretime(DateUtils.addDateTime(lt.getCreatetime(),0,10,0));
		return lt;
	}


}
